package utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @author zsy
 * @Description:
 * @create 2018-01-05 10:04
 **/
public class ReflectUtils {

    private static final String TYPE_NAME_PREFIX = "class ";

    /**
     * 获取泛型类型
     *
     * @author zsy
     * @date 2018/1/5 10:06
     */
    public static Type[] getGenericType(Field field) {
        field.setAccessible(true);
        Type type = field.getGenericType();
        if (!ParameterizedType.class.isAssignableFrom(type.getClass())) {
            return null;
        }
        return ((ParameterizedType) type).getActualTypeArguments();
    }

    /**
     * 通过Type获取class名称
     *
     * @return java.lang.String
     * @author zsy
     * @date 2018/1/5 10:11
     */
    public static String getClassName(Type type) {
        if (type == null) {
            return "";
        }
        String className = type.toString();
        if (className.startsWith(TYPE_NAME_PREFIX)) {
            className = className.substring(TYPE_NAME_PREFIX.length());
        }
        return className;
    }

    /**
     * @Description: 通过type获取class
     * @Author: zsy
     * @Date: 2018/1/5 10:40
     */
    public static Class<?> getClassByType(Type type) throws ClassNotFoundException {
        String className = getClassName(type);
        if (className == null || className.isEmpty()) {
            return null;
        }
        return Class.forName(className);
    }
}
